package com.umeox.zikrringtest.single_test

import android.util.Log
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.umeox.sdk_ring.RingProxy
import com.umeox.sdk_ring.UMRingSdk
import com.umeox.sdk_ring.core.RingCommandParser
import com.umeox.sdk_ring.protocol.IEmptyAppProtocol
import com.umeox.zikrringtest.App
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.Date
import java.util.TimeZone
import kotlin.math.abs

class SingleTestViewModel : ViewModel(), IEmptyAppProtocol {

    lateinit var ringProxy: RingProxy

    private var showLoading = MutableLiveData<Boolean>()

    fun showLoadingDialog() {
        showLoading.postValue(true)
    }

    fun hideLoadingDialog() {
        showLoading.postValue(false)
    }


    private val ringInfo = RingInfo()

    val ringInfoObserver = MutableLiveData(ringInfo)
    val pkeyObserver = MutableLiveData("")

    fun initInteraction(macAddress: String) {
        ringInfo.macAddress = macAddress
        ringInfoObserver.postValue(ringInfo)
        ringProxy = UMRingSdk.createRingProxy(macAddress).apply {
            addAppProtocolObserver(this@SingleTestViewModel)
        }
    }

    override fun onCacheDataCallback(
        startTime: String,
        endTime: String,
        num: Int,
        tick: String,
        endFlag: Int
    ) {
        Log.d(
            "FunctionalViewModel",
            "收到缓存数据  startTime = $startTime  endTime = $endTime  num = $num  tick = $tick  endFlag = $endFlag"
        )
        ringProxy.getPrayerCountInformation(tick)
    }

    override fun onSettingDeviceLanguageCallback() {
        ringProxy.getDeviceConfigInfo()
    }

    override fun onSetScreenRestTime() {
        ringProxy.getDeviceConfigInfo()
    }

    override fun onSetPrayerRemindConfig() {
        ringProxy.getDeviceConfigInfo()
    }

    override fun onSetCustomCountReminder() {
        ringProxy.getDeviceConfigInfo()
    }

    override fun onBatteryPowerCallback(
        status: String,
        bat: String,
        version: String,
        versionName: String,
        buildTime: String
    ) {
        ringInfo.state = "已连接"
        ringInfo.connectState = true
        ringInfo.power = bat
        ringInfo.version = versionName
        ringInfoObserver.postValue(ringInfo)
    }

    override fun onRealTimeCountCallback(
        num: Int,
        tick: String,
        taskStatus: Int,
        currentTaskNumber: Int
    ) {
        ringInfo.realTimeNumber = "$num"
        ringInfo.taskStatus = parseTaskStatus(taskStatus)
        ringInfo.taskCurrentNumber = "$currentTaskNumber"
        ringInfoObserver.postValue(ringInfo)
    }

    private fun parseTaskStatus(taskStatus: Int): String {
        return when (taskStatus) {
            0 -> "无任务"
            1 -> "有任务未开始"
            2 -> "任务进行中"
            3 -> "任务中断或者取消结束"
            4 -> "任务完成"
            else -> ""
        }
    }

    override fun onDeviceScreenBrightnessCallback() {
        ringProxy.getDeviceConfigInfo()
    }

    override fun onDataCacheSizeCallback(
        num: Int,
        currentRealTimeNumber: Int,
        currentTaskNumber: Int
    ) {
        ringInfo.realTimeNumber = "$currentRealTimeNumber"
        ringInfo.taskCurrentNumber = "$currentTaskNumber"
        ringInfoObserver.postValue(ringInfo)
    }

    override fun onDeviceConfigInfoCallback(
        isPositive: Boolean,
        isOpenPray: Int,
        chartingStartTime: String,
        chartingEndTime: String,
        light: Int,
        languageType: Int,
        timeInterval: Int,
        supportTaskMode: Boolean,
        taskStatus: Int,
        targetNumber: Int,
        taskId: Int,
        remarks: String,
        protocolVersion: String
    ) {
        ringInfo.screen = if (isPositive) "正" else "反"
        ringInfo.prayer = if (isOpenPray == 1) "开" else "关"
        ringInfo.chanting = "$chartingStartTime#$chartingEndTime#$timeInterval"
        ringInfo.light = "$light"
        ringInfo.language = RingCommandParser.parseDeviceLanguage(languageType)
        ringInfo.supportTask = if (supportTaskMode) {
            "是"
        } else {
            "否"
        }
        ringInfo.taskStatus = parseTaskStatus(taskStatus)
        ringInfo.targetNumber = "$targetNumber"
        ringInfo.taskID = "$taskId"
        ringInfo.protocolVersion = protocolVersion
        ringInfoObserver.postValue(ringInfo)
        viewModelScope.launch {
            delay(1000)
            ringProxy.getPrayerRemindConfig()
        }
    }

    private var sync = false

    override fun requestTimeSync() {
        viewModelScope.launch(Dispatchers.Main) {
            if (sync) {
                Log.d(
                    "UMRing_FunctionalViewModel",
                    "同步中..."
                )
                return@launch
            }
            sync = true
            ringProxy.syncCurrentTimeAndTimeFormat(null, null, true, getCurrentTimeZone())
            delay(1000)
            ringProxy.getDeviceBatteryPower()
            delay(1000)
            ringProxy.getDeviceConfigInfo()
            delay(1000)
            ringProxy.getSc01DeviceInfo()
            delay(1000)
            ringProxy.getDeviceCacheData()
            delay(1000)
            ringProxy.setUserInfo(34, 1, 170, 65, 200, 50, 30)
            delay(1000)
            ringProxy.pkeyOperation(false, "")
            delay(1000)
            ringProxy.gsensorTest()
            sync = false
        }
    }

    /**
     * 可简化计算过程 为了方便理解 没有简化
     */
    private fun getCurrentTimeZone(): Double {
        val now = Date()
        val zone = TimeZone.getDefault()
        val id = zone.id
        val timeZone1 = TimeZone.getTimeZone(id)
        val timeZone2 = TimeZone.getTimeZone("UTC")

        val currentOffsetFromUTC = if (timeZone1.inDaylightTime(now)) {
            timeZone1.dstSavings + timeZone1.rawOffset
        } else {
            0 + timeZone1.rawOffset
        }

        val serverOffsetFromUTC = if (timeZone2.inDaylightTime(now)) {
            timeZone2.dstSavings + timeZone2.rawOffset
        } else {
            0 + timeZone2.rawOffset
        }

        val isNegativeNumber = currentOffsetFromUTC < 0

        val secondOffset = abs(abs(serverOffsetFromUTC) - currentOffsetFromUTC) / 1000
        val hour = secondOffset / 3600
        val minute = secondOffset % 3600 / 60
        return if (isNegativeNumber) {
            -1.0 * (hour + minute / 60.0)
        } else {
            hour + minute / 60.0
        }
    }

    override fun onGetTasbihTaskInfoCallback(
        targetNumber: Int,
        taskId: Int,
        startTime: String,
        endTime: String,
        tick: String
    ) {

        ringInfo.targetNumber = "$targetNumber"
        ringInfo.taskID = "$taskId"
        ringInfo.taskStartTime = startTime
        ringInfo.taskEndTime = endTime
        ringInfoObserver.postValue(ringInfo)
        viewModelScope.launch {
            delay(1000)
            Log.d(
                "FunctionalViewModel",
                "收到任务缓存数据  startTime = $startTime  endTime = $endTime  targetNumber = $targetNumber  tick = $tick  taskId = $taskId"
            )
            ringProxy.getTasbihTaskInfo(tick)
            delay(5000)
            ringInfo.targetNumber = "-"
            ringInfo.taskID = "-"
            ringInfo.taskStartTime = "-"
            ringInfo.taskEndTime = "-"
            ringInfo.taskStatus = ""
            ringInfoObserver.postValue(ringInfo)
        }
    }

    override fun onSettingCustomizeConventionCallback() {
        super.onSettingCustomizeConventionCallback()
        ringProxy.getDeviceConfigInfo()
    }

    override fun onChantingRemindersSettingCallback() {
        ringProxy.getDeviceConfigInfo()
    }

    override fun onSettingPrayerRemindersCallback() {
        ringProxy.getDeviceConfigInfo()
    }

    override fun onGetPrayerRemindConfig(
        restTime: Int,
        configs: Array<Array<Int>>,
        normal33: Boolean,
        normal100: Boolean,
        customValue: Int
    ) {
        ringInfo.restTime = "$restTime"
        ringInfo.normal33 = "$normal33"
        ringInfo.normal100 = "$normal100"
        ringInfo.customValue = "$customValue"
        ringInfoObserver.postValue(ringInfo)
    }

    override fun onGetCurrentStep(step: Int) {
        ringInfo.step = "$step"
        ringInfoObserver.postValue(ringInfo)
    }

    override fun onPkeyOperation(pkey: String) {
        pkeyObserver.postValue(pkey)
    }

    override fun onGsensorTest(gsensorId: Int, status: Int, datas: Array<Int>) {
        if (status == 1) {
            ringInfo.algorithmStatus = "正常"
            ringInfoObserver.postValue(ringInfo)
        } else {
            ringInfo.algorithmStatus = "异常"
            ringInfoObserver.postValue(ringInfo)
        }

        val zeroSize = datas.filter {
            it == 0
        }.size

        val v1200V1 = (datas[0]*datas[0] + datas[1]*datas[1] + datas[2]*datas[2]) > 1200 * 1200
        val v1200V2 = (datas[3]*datas[3] + datas[4]*datas[4] + datas[5]*datas[5]) > 1200 * 1200
        val v1200V3 = (datas[6]*datas[6] + datas[7]*datas[7] + datas[8]*datas[8]) > 1200 * 1200

        if (zeroSize >= 7) {
            ringInfo.gsensor = "无sensor"
            ringInfoObserver.postValue(ringInfo)
            return
        }

        if (v1200V1 || v1200V2 || v1200V3) {
            ringInfo.gsensor = "有偏差"
            ringInfoObserver.postValue(ringInfo)
            return
        }

        if (datas.contains(7999)) {
            ringInfo.gsensor = "传感器已坏"
            ringInfoObserver.postValue(ringInfo)
            return
        }

        ringInfo.gsensor = "传感器正常"
        ringInfoObserver.postValue(ringInfo)
    }

    override fun onDeviceRadarTest(enable: Boolean) {
        viewModelScope.launch(Dispatchers.Main) {
            Toast.makeText(App.application,"设备雷达测试打开状态：$enable",Toast.LENGTH_SHORT).show()
        }
    }

    override fun onGetDeviceMotorAgingTestResul() {
        viewModelScope.launch(Dispatchers.Main) {
            Toast.makeText(App.application,"已收到设备雷达返回触发结果",Toast.LENGTH_SHORT).show()
            ringProxy.getDeviceMotorAgingTestResul()
        }
    }

    override fun onGetTofResult(status: Int, distance: Int) {
        viewModelScope.launch(Dispatchers.Main) {
            Toast.makeText(App.application,"设备上发tof（距感）状态数据: status = $status   distance = $distance",Toast.LENGTH_SHORT).show()
        }
    }

    override fun onTofCalibration1(status: Int) {
        viewModelScope.launch(Dispatchers.Main) {
            Toast.makeText(App.application,"tof校准指令1反馈: status = $status",Toast.LENGTH_SHORT).show()
        }
    }

    override fun onTofCalibration2(status: Int) {
        viewModelScope.launch(Dispatchers.Main) {
            Toast.makeText(App.application,"tof校准指令2反馈: status = $status",Toast.LENGTH_SHORT).show()
        }
    }

    override fun onGetWorshipCacheData(
        updateTime: String,
        fajrCount: Int,
        dhuhrCount: Int,
        asrCount: Int,
        maghribCount: Int,
        ishaCount: Int,
        tick: String,
        endFlag: Int
    ) {
        Log.d("xcl_debug", "获取到离线数据 updateTime:$updateTime   fajrCount:$fajrCount   dhuhrCount:$dhuhrCount   asrCount:$asrCount   maghribCount:$maghribCount   ishaCount:$ishaCount   tick:$tick   endFlag$endFlag")
        ringProxy.getWorshipCacheData(tick)
    }

    override fun onConnecting() {
        ringInfo.state = "连接中"
        ringInfo.connectState = false
        ringInfo.power = "-"
        ringInfo.version = "-"
        ringInfoObserver.postValue(ringInfo)
    }

    override fun onConnected() {
        ringInfo.state = "已连接"
        ringInfo.connectState = true
        ringInfo.power = "-"
        ringInfo.version = "-"
        ringInfo.taskStatus = ""
        ringInfoObserver.postValue(ringInfo)
        hideLoadingDialog()
    }

    override fun onDisconnected() {
        ringInfo.state = "未连接"
        ringInfo.connectState = false
        ringInfo.power = "-"
        ringInfo.version = "-"
        ringInfoObserver.postValue(ringInfo)
        hideLoadingDialog()
    }

    override fun onConnectTimeout() {
        ringInfo.state = "连接超时"
        ringInfo.connectState = false
        ringInfo.power = "-"
        ringInfo.version = "-"
        ringInfoObserver.postValue(ringInfo)
        hideLoadingDialog()
    }

    fun setTask(etTargetNumber: Int, etTaskId: Int) {
        ringInfo.targetNumber = "$etTargetNumber"
        ringInfo.taskID = "$etTaskId"
        ringInfoObserver.postValue(ringInfo)
    }

    override fun onGetSc01DeviceInfo(
        battery: Int,
        lightTime: Int,
        light: Int,
        protocolVersion: String,
        softwareVersion: String,
        audioEnable: Boolean
    ) {
        ringInfo.sc01VolumeEnable = "$audioEnable"
        ringInfoObserver.postValue(ringInfo)
    }

    override fun onSetSc01AudioEnable() {
        viewModelScope.launch(Dispatchers.Main) {
            delay(500)
            ringProxy.getSc01DeviceInfo()
        }
    }
}

class RingInfo {
    var connectState: Boolean = false
    var macAddress: String = "-"
    var state: String = "未连接"
    var power: String = "-"
    var version: String = "-"
    var screen: String = "-"
    var prayer: String = "-"
    var chanting: String = "-"
    var light: String = "-"
    var language: String = "-"
    var supportTask: String = "否"
    var realTimeNumber: String = "0"
    var taskStatus: String = ""
    var taskCurrentNumber: String = "0"
    var targetNumber: String = "-"
    var taskStartTime: String = "-"
    var taskEndTime: String = "-"
    var taskID: String = "-"
    var protocolVersion: String = "0"
    var restTime: String = "-"
    var step: String = "-"
    var normal33: String = "-"
    var normal100: String = "-"
    var customValue: String = "-"
    var gsensor: String = "-"
    var algorithmStatus: String = "-"
    var sc01VolumeEnable: String = "false"
}